<?php

namespace app\modules\Merchant\service;

use app\modules\Merchant\models\dianpuwalletapplyModel;
use Illuminate\Database\Capsule\Manager as DB;
use app\modules\Merchant\models\dianpuwalletapplylogModel;

class Withdraw
{
    public static function apply($params = [])
    {
        try {
            $params['apply_sn'] = self::generateApplySn($params['member_id']);
            $params['created_at'] = timestamp();
            $params['updated_at'] = $params['created_at'];
            return DB::transaction(function () use ($params){
                $apply_id = dianpuwalletapplyModel::query()->insertGetId($params);
                $do_money = bcsub(0, $params['money'], 2);
                if(false === DianpuMoney::moneyChange($do_money, $params['dianpu_id'], 'dianpuWithdraw', $apply_id, "会员{$params['member_id']}为店铺ID{$params['dianpu_id']}申请提现，扣除{$params['money']}元", 'user', $params['member_id'])){
                    throw new \Exception('修改店铺金额失败！');
                }
                if(false === self::addLog($apply_id, 'apply', "会员{$params['member_id']}为店铺ID{$params['dianpu_id']}申请提现{$params['money']}元", 'user', $params['member_id'])){
                    throw new \Exception('提现申请出错！');
                }
                return $apply_id;
            });
        } catch (\Exception $e) {
            return false;
        }
    }

    // 生成提现编号
    public static function generateApplySn($user_id = 0)
    {
        $rand = $user_id < 9999 ? mt_rand(100000, 99999999) : mt_rand(100, 99999);
        $card_sn = date('Yzhis') . $rand;

        $id = str_pad($user_id, (24 - strlen($card_sn)), '0', STR_PAD_BOTH);

        return 'Mtx'.$card_sn . $id;
    }

    public static function addLog($apply_id, $event, $remark, $oper_type = 'system', $oper_id = 0)
    {
        try {
            $allEvent = dianpuwalletapplylogModel::getAllEvent();
            if(!in_array($event, array_keys($allEvent))){
                throw new \Exception("事件:{$event},ID:{$apply_id}");
            }
            $input = [
                'apply_id'=>$apply_id,
                'event'=>$event,
                'event_id'=>$apply_id,
                'remark'=>$remark,
                'oper_type'=>$oper_type,
                'oper_id'=>$oper_id,
                'created_at'=>timestamp(),
            ];
            return DB::transaction(function () use ($input){
                return dianpuwalletapplylogModel::query()->insert($input);
            });
        } catch (\Exception $e){
            trace("Merchant Withdraw Log Error: {$e->getMessage()}");
            return false;
        }
    }
}